<template>
  <div v-loading="loading">
    <el-form ref="form" :model="form" :rules="rules" label-width="120px" class="dataForm">
      <el-row>
        <el-col :span="24">
          <el-form-item :label="$t('提醒标题')" prop="title">
            <el-input v-model="form.title" :placeholder="$t('提醒标题')" show-word-limit maxlength="50" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('提醒状态')" prop="status">
            <el-switch
              v-model="form.status"
              active-color="#13ce66"
              inactive-color="#ff4949"
              :active-text="$t('开启')"
              :inactive-text="$t('关闭')"
              :active-value="'Y'"
              :inactive-value="'N'"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('提醒方式')" prop="method">
            <el-checkbox-group v-model="form.method" size="small">
              <el-checkbox
                v-for="(dict, index) in reminderModeOptions"
                :key="index"
                :label="dict.dictValue"
              >{{ $t(dict.dictLabel) }}</el-checkbox>
            </el-checkbox-group>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('提醒频率')" prop="frequency">
            <el-radio-group v-model="form.frequency">
              <el-radio
                v-for="dict in reminderFrequencyOptions"
                :key="dict.dictValue"
                :label="dict.dictValue"
              >{{ $t(dict.dictLabel) }}
              </el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col v-if="form.frequency === 'TIMER'" :span="12">
          <el-form-item :label="$t('定时提醒时间')" prop="time">
            <el-date-picker
              v-model="form.time"
              clearable
              style="width: 200px"
              type="datetime"
              value-format="yyyy-MM-dd HH:mm:ss"
              format="yyyy-MM-dd HH:mm"
              :picker-options="pickerOptions"
              :placeholder="$t('定时提醒时间')"
            />
          </el-form-item>
        </el-col>
        <el-col v-if="form.frequency === 'FREQUENCY'" :span="24">
          <el-form-item prop="cron">
            <Cron v-model="form.cron" :cron-value.sync="form.frequencyCronValue" />
          </el-form-item>
        </el-col>
        <el-col v-if="isShowDealTeam" :span="12">
          <el-form-item :label="$t('是否提醒团队成员')" prop="team">
            <el-radio-group v-model="form.team">
              <el-radio
                v-for="item in yesNoOptions"
                :key="item.dictValue"
                :label="$t(item.dictValue)"
              > {{ $t(item.dictLabel) }}
              </el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>

        <el-col v-if="isShowRole" :span="12">
          <el-form-item :label="$t('提醒角色')" prop="role">
            <el-select v-model="form.role" :placeholder="$t('其他提醒角色')" filterable clearable>
              <el-option
                v-for="item in roleOptions"
                :key="item.roleId"
                :label="$t(item.roleName)"
                :value="item.roleId"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col v-if="isShowUser" :span="12">
          <el-form-item :label="$t('提醒用户')" prop="user">
            <user-select v-model="form.user" :placeholder="$t('其他提醒用户')" multiple />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item :label="$t('提醒内容')" prop="context">
            <EditorTxt v-model="form.context" :show-cus-btn="showTextCusBtn" :placeholder="$t('提醒内容')" />
          </el-form-item>
        </el-col>
      </el-row>
      <br>
      <div v-show="false">
        <div class="area-header">
          <span class="area-header-title">{{ $t('关键字列表') }}</span>
        </div>
        <el-table class="nowrapTable formTable" :data="form.remindKeyword" border>
          <el-table-column :label="$t('字段名称')" align="center">
            <template slot="header" slot-scope="{}">
              <i style="color: #ff4949;margin-right: 4px;">*</i>
              <span>{{ $t('字段名称') }}</span>
            </template>
            <template slot-scope="scope">
              <el-form-item :prop="'remindKeyword.' + scope.$index + '.fieldName'" :rules="configNodeKeywordRules.fieldName">
                <el-input v-model="scope.row.fieldName" :placeholder="$t('字段名称')" />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column :label="$t('备注')" align="center">
            <template slot-scope="scope">
              <el-form-item>
                <el-input v-model="scope.row.remark" :placeholder="$t('备注')" />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column :label="$t('操作')" align="center" width="80">
            <template slot-scope="scope">
              <el-button size="mini" type="text" icon="el-icon-delete" @click="delTemplate(scope.$index, scope.row)">
                {{ $t('删除') }}
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <div class="tol">
          <el-button type="primary" icon="el-icon-plus" size="mini" @click="addTemplate">{{ $t("添加") }}</el-button>
        </div>
      </div>
    </el-form>
    <div slot="footer" class="dialog-footer" style="text-align: right;">
      <el-button @click="cancel">{{ $t('取消') }}</el-button>
      <el-button v-if="!waiteSave" v-hasPermi="hasPermi" type="primary" @click="submitForm">{{ $t('保存') }}</el-button>
      <el-button v-if="waiteSave" v-hasPermi="hasPermi" type="primary" @click="saveForm">{{ $t('确定') }}</el-button>
    </div>
  </div>
</template>

<script>
import { allRole } from '@/api/system/role'
import { treeselect } from '@/api/system/dept'
import { getByDataIdAndType, saveDataSysRemindEvent } from '@/api/system/sysremindevent/sysRemindEvent'
import EditorTxt from '@/components/Tinymce'
import Cron from '@/components/Cron'
export default {
  components: {
    EditorTxt,
    Cron
  },
  props: {
    // 提醒类型
    reminderType: {
      type: String,
      required: true
    },
    // 是否展示团队成员选项
    isShowDealTeam: {
      type: Boolean,
      default: () => false
    },
    // 是否展示角色选项
    isShowRole: {
      type: Boolean,
      default: () => false
    },
    // 是否展示用户选项
    isShowUser: {
      type: Boolean,
      default: () => true
    },
    // 父级表单的form名称
    // topFormName: {
    //   type: Boolean,
    //   default: () => 'form'
    // },
    // 保存权限
    hasPermi: {
      type: String,
      default: () => ''
    },
    // 是否跟随表单保存, 即点击页面确定后不保存数据, 等待父组件保存后再保存该提醒
    waiteSave: {
      type: Boolean,
      default: () => false
    },
    showTextCusBtn: {
      type: Boolean,
      default: () => false
    }
  },
  data() {
    return {
      // 遮盖层
      loading: false,
      form: {
        remindKeyword: []
      },
      rules: {
        status: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }],
        title: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }],
        method: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }],
        team: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }],
        frequency: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }],
        context: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }],
        time: [{ required: true, validator: this.checkTime, trigger: 'blur' }],
        cron: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }]
      },
      configNodeKeywordRules: {
        fieldName: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }]
      },
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() < Date.now()
        },
        shortcuts: [{
          text: this.$t('5分钟后'),
          onClick(picker) {
            const start = new Date()
            start.setTime(start.getTime() + 60 * 1000 * 5)
            picker.$emit('pick', start)
          }
        }, {
          text: this.$t('10分钟后'),
          onClick(picker) {
            const start = new Date()
            start.setTime(start.getTime() + 60 * 1000 * 10)
            picker.$emit('pick', start)
          }
        }, {
          text: this.$t('30分钟后'),
          onClick(picker) {
            const start = new Date()
            start.setTime(start.getTime() + 60 * 1000 * 30)
            picker.$emit('pick', start)
          }
        }, {
          text: this.$t('明天'),
          onClick(picker) {
            const date = new Date()
            date.setTime(date.getTime() + 3600 * 1000 * 24)
            picker.$emit('pick', date)
          }
        }, {
          text: this.$t('7天后'),
          onClick(picker) {
            const date = new Date()
            date.setTime(date.getTime() + 3600 * 1000 * 24 * 7)
            picker.$emit('pick', date)
          }
        }, {
          text: this.$t('30天后'),
          onClick(picker) {
            const date = new Date()
            date.setTime(date.getTime() + 3600 * 1000 * 24 * 30)
            picker.$emit('pick', date)
          }
        }]
      },
      // 提醒方式字典
      reminderModeOptions: [],
      // 是否字典
      yesNoOptions: [],
      // 角色选项
      roleOptions: [],
      // 提醒频率字典
      reminderFrequencyOptions: []
    }
  },
  watch: {},
  created() {
  },
  mounted() {
    // 提醒方式字典
    this.getDicts('reminder_mode').then(response => {
      console.log(response.data)
      this.reminderModeOptions = response.data
    })
    // 是否字典
    this.getDicts('sys_yes_no').then(response => {
      this.yesNoOptions = response.data
    })
    // 是否字典
    this.getDicts('work_flow_status').then(response => {
      this.workFlowStatusOptions = response.data
    })
    // 角色
    allRole().then(response => {
      this.roleOptions = response.data
    })
    // 部门树
    treeselect().then(response => {
      this.deptOptions = response.data
    })
    // 提醒频率
    this.getDicts('reminder_frequency').then(response => {
      this.reminderFrequencyOptions = response.data
    })
  },
  methods: {
    init(dataId) {
      this.reset()
      if (!this.isEmpty(dataId)) {
        this.form.dataId = dataId
        this.loading = true
        getByDataIdAndType(dataId, this.reminderType).then(response => {
          if (response.data !== null) {
            this.form = response.data
          }
          console.log(response)
          this.loading = false
        })
      }
      // 获取付表单的所有字段
      // if (this.$parent.$parent.$refs[this.topFormName].fields) {
      //   this.$parent.$parent.$refs[this.topFormName].fields.forEach(item => {
      //     console.log(item.label + ' ==> ' + item.fieldValue)
      //   })
      // }
    },
    initData(data) {
      this.form = data
    },
    reset() {
      this.form = {
        status: undefined,
        method: [],
        title: undefined,
        team: 'N',
        role: undefined,
        user: [],
        frequency: 'TIMER',
        context: undefined,
        time: undefined,
        cron: undefined,
        remindKeyword: []
      }
      this.resetForm('form')
    },
    cancel() {
      if (this.$parent.$parent.remindOpen) {
        this.$parent.$parent.remindOpen = false
      }
      if (this.$parent.$parent.$parent.remindOpen) {
        this.$parent.$parent.$parent.remindOpen = false
      }
    },
    checkTime(rule, value, callback) {
      if (this.isEmpty(value)) {
        callback(new Error(this.$t('必填信息')))
      } else {
        const time = new Date(value)
        if (time.getTime() < new Date().getTime()) {
          callback(new Error('不能早于当前时间'))
        } else {
          callback()
        }
      }
    },
    saveForm() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          this.form.type = this.reminderType
          this.$emit('saveRemindEvent', JSON.stringify(this.form))
          this.cancel()
        } else {
          this.locationError(document)
        }
      })
    },
    submitForm() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          this.loading = true
          this.form.type = this.reminderType
          console.log(this.form)
          saveDataSysRemindEvent(this.form).then(response => {
            console.log(response)
            if (response.code === 200) {
              this.form = response.data
              this.msgSuccess(this.$t(response.msg))
              this.cancel()
            } else {
              this.msgError(this.$t(response.msg))
            }
            this.loading = false
          })
        } else {
          this.locationError(document)
        }
      })
    },
    addTemplate() {
      const row = {
        id: undefined,
        fieldName: undefined,
        remark: undefined
      }
      if (!(this.form.remindKeyword instanceof Array)) {
        this.$set(this.form, 'remindKeyword', [])
      }
      this.$nextTick(() => {
        this.form.remindKeyword.push(row)
      })
    },
    // 删除关键字列表
    delTemplate(index, row) {
      const id = row.id
      if (id !== undefined && id !== '' && id != null) {
        this.$confirm(this.$t('是否确认删除?'), this.$t('警告'), {
          confirmButtonText: this.$t('确定'),
          cancelButtonText: this.$t('取消'),
          type: 'warning'
        })
          .then(function() {
          }).then(() => {
          this.form.remindKeyword.splice(index, 1)
          return this.msgSuccess(this.$t('删除成功'))
        })
        .catch(function() {})
      } else {
        this.form.remindKeyword.splice(index, 1)
      }
    }
  }
}
</script>

<style scoped>
/deep/ .el-button--text {
  display: none !important;
}
</style>
